package cwiczenia;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf8");
        PrintWriter pw = response.getWriter();
        
        HttpSession session = request.getSession();

        if (session.getAttribute("login") == null) {
            if (request.getParameter("user") == null || request.getParameter("pass") == null)
                pw.print("<html><body><h1>Niezalogowany</h1>" +
                        "<form method=\"POST\"" + " action=\"Login\">" +
                        "user: <input type=\"text\" size=\"20\" name=\"user\"><br/>" +
                        "pass: <input type=\"password\" size=\"20\" name=\"pass\"><br/>" +
                        "<input type=\"submit\" name=\"submit\" Value=\"Submit\">" +
                        "</form>" +
                        "</body></html>");
            else {
                if (userOK(request.getParameter("user"), request.getParameter("pass"))) {
                    session.setAttribute("login", request.getParameter("user"));
                    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/File");
                    dispatcher.forward(request, response);
                } else {
                    pw.print("Hehe... ]:->");
                }
            }

        } else {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/File");
            dispatcher.forward(request, response);
        }

        pw.close();
    }

    private boolean userOK(String user, String pass) {
        if (getInitParameter(user) != null && getInitParameter(user).equals(pass))
            return true;
        return false;
    }
}
